<template>
  <view class="h-[100vh] flex flex-col overflow-hidden bg-white">
    <S1Header :title="pageMode === 'edit' ? '编辑货品' : '新增货品'" :on-back="handleBack" />
    <scroll-view class="form-scroll" scroll-y>
      <!-- 基本信息 -->
      <view class="section-title">
        基本信息
      </view>
      <view class="form-row">
        <text class="form-label">
          货品名称
        </text>
        <input v-model="form.goodsName" class="form-input" placeholder="请输入商品名称">
      </view>
      <view class="form-row" @click="showCategoryPicker = true">
        <text class="form-label">
          货品分类
        </text>
        <view class="form-input">
          {{ getCategoryDisplayText() }}
          <image src="/static/images/select.png" class="right-arrow-img" />
        </view>
      </view>
      <view class="form-row image-row">
        <view>
          <text class="form-label">
            上传图片
          </text>
          <view class="form-desc">
            请保证图片的清晰度(400*400)
          </view>
        </view>
        <view class="upload-area" @click="chooseImage">
          <image v-if="form.imageUrl" :src="form.imageUrl" class="upload-preview" mode="aspectFill" />
          <view v-else class="camera-icon">
            <text class="icon-text">
              &#128247;
            </text>
          </view>
        </view>
      </view>

      <!-- 规格单位 -->
      <view class="section-title">
        <text>规格单位</text>
        <view class="config-btn" @click="onConfig('unit')">
          扩展单位
          <image src="/static/images/select.png" class="right-arrow-img" />
        </view>
      </view>
      <view class="unit-card-v2">
        <view class="unit-row-v2">
          <text class="unit-label-v2">
            销售单位
          </text>
          <view class="unit-select-v2" @click="handleSelectSaleUnit">
            {{ form.saleUnit || "请选择" }}
          </view>
          <view class="radio-wrap-v2" @click="form.defaultPriceUnit = 'sale'">
            <view
              class="radio-circle-v2" :class="[
                form.defaultPriceUnit === 'sale' ? 'active' : '',
              ]"
            />
            <text
              class="radio-label-v2" :class="[
                form.defaultPriceUnit === 'sale' ? 'active' : '',
              ]"
            >
              默认计价
            </text>
          </view>
        </view>
        <view class="divider-v2" />
        <view v-for="(item, idx) in guige" :key="item.id" class="border-b border-[#f0f0f0] border-b-solid">
          <view class="unit-row-v2">
            <text class="unit-label-v2">
              单位
            </text>
            <picker :range="unitList" range-key="name" @change="(e) => selectUnitPicker(e, idx)">
              <view class="unit-select-v2">
                {{ item.unit || "请选择" }}
              </view>
            </picker>
            <view class="radio-wrap-v2" @click="form.defaultPriceUnit = `extend${idx}`">
              <view
                class="radio-circle-v2" :class="[
                  form.defaultPriceUnit === `extend${idx}` ? 'active' : '',
                ]"
              />
              <text
                class="radio-label-v2" :class="[
                  form.defaultPriceUnit === `extend${idx}` ? 'active' : '',
                ]"
              >
                默认计价
              </text>
            </view>
          </view>
          <view class="unit-row-v2">
            <text class="unit-label-v2">
              定装规格
            </text>
            <view class="spec-group">
              <input v-model="item.num" class="spec-input" type="digit">
              <view class="spec-desc">
                <text>{{ item.unit || "单位" }}=1{{ form.saleUnit || "箱" }}</text>
              </view>
            </view>
            <view class="delete-btn-v2 i-mdi-delete" @click="removeExtendUnit(idx)" />
          </view>
        </view>
      </view>

      <!-- 附加费 -->
      <view class="section-gap" />
      <view class="section-title">
        <text class="fujiafei-title-text">
          附加费配置
        </text>
        <view class="config-btn" @click="onConfig('fee')">
          新增费用
          <image src="/static/images/select.png" class="right-arrow-img" />
        </view>
      </view>

      <!-- 附加费列表 -->
      <view v-if="select_fujiafei_list.length === 0" class="form-row">
        <text class="form-label">
          暂无附加费
        </text>
        <view class="form-input">
          <text class="text-gray-400">
            点击新增费用添加附加费
          </text>
        </view>
      </view>

      <view
        v-for="(item, index) in select_fujiafei_list" :key="item.id" class="fujiafei-item"
        @click="editFujiafei(index)"
      >
        <view class="fujiafei-content">
          <text class="fujiafei-name">
            {{ item.name || '附加费' }}
            <text class="mt-4rpx text-22rpx text-[#999]">
              {{
                getPayerText(item.method) }}
            </text>
          </text>
          <text class="fujiafei-amount">
            {{ item.rate || '0' }}{{ getCalculationUnit(item.type) }}
          </text>
        </view>
      </view>
    </scroll-view>
    <view class="section-gap" />
    <view class="single-card">
      <view class="form-row no-border switch-row">
        <text class="form-label-switch">
          是否允许超库存销售
        </text>
        <u-switch v-model="form.allowOverStock" />
      </view>
    </view>
    <view class="save-btn-wrap">
      <u-button
        type="primary" shape="circle" :text="pageMode === 'edit' ? '更新' : '保存'" custom-style="width: 100%"
        @click="handleSave"
      />
    </view>
  </view>

  <!-- 分类选择器 -->
  <up-picker
    ref="categoryPickerRef" :show="showCategoryPicker" :columns="categoryColumns" title="选择货品分类"
    :loading="categoryLoading" @confirm="onCategoryConfirm" @cancel="showCategoryPicker = false" @close="showCategoryPicker = false"
    @change="onCategoryChange"
  />

  <!-- 单位选择弹窗 -->
  <up-popup :show="showUnitSelector" mode="bottom" :round="10" @close="showUnitSelector = false">
    <view>
      <view class="mb-10rpx w-full flex justify-center" @click="showUnitSelector = false">
        <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
      </view>
      <view class="filter-content p-30rpx pb-10rpx">
        <view class="mb-16rpx flex items-center">
          <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
          <text class="text-32rpx text-[#333]">
            选择单位
          </text>
        </view>
        <scroll-view :scroll-y="true" class="unit-scroll-container">
          <view
            v-for="(item, index) in unitList" :key="index"
            class="border-b border-[#f0f0f0] px-0 py-24rpx text-center text-32rpx text-[#333]"
            @click="selectUnit(item)"
          >
            {{ item?.name || "" }}
          </view>
        </scroll-view>
      </view>
    </view>
  </up-popup>

  <!-- 附加费选择弹窗 -->
  <up-popup :show="showFujiafeiSelector" mode="bottom" :round="10" @close="showFujiafeiSelector = false">
    <view>
      <view class="mb-10rpx w-full flex justify-center" @click="showFujiafeiSelector = false">
        <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
      </view>
      <view class="filter-content p-30rpx pb-10rpx">
        <view class="mb-16rpx flex items-center justify-between">
          <view class="flex items-center">
            <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
            <text class="text-32rpx text-[#333]">
              选择附加费
            </text>
          </view>
          <view class="flex gap-20rpx">
            <text class="text-28rpx text-[#666]" @click="showFujiafeiSelector = false">
              取消
            </text>
            <text class="text-28rpx text-[#07c160]" @click="confirmSelectFujiafei">
              确定
            </text>
          </view>
        </view>
        <scroll-view :scroll-y="true" class="fujiafei-scroll-container">
          <view
            v-for="(item, index) in fujiafeiList" :key="index"
            class="flex items-center justify-between border-b border-[#f0f0f0] px-0 py-24rpx text-32rpx text-[#333]"
            @click="toggleFujiafeiSelection(item)"
          >
            <view class="flex items-center">
              <view
                class="mr-20rpx h-32rpx w-32rpx flex items-center justify-center border-2rpx rounded-8rpx" :class="[
                  selectedFujiafeiIds.includes(item.id) ? 'border-[#07c160] bg-[#07c160]' : 'border-[#ddd]',
                ]"
              >
                <text v-if="selectedFujiafeiIds.includes(item.id)" class="text-20rpx text-white">
                  ✓
                </text>
              </view>
              <view class="flex flex-col items-start">
                <text>{{ item.name }}</text>
              </view>
            </view>
            <view class="flex items-center">
              <text class="text-28rpx text-[#666]">
                {{ item.rate || '0' }}{{ getCalculationUnit(item.type) }}
              </text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </up-popup>

  <!-- 附加费编辑弹窗 -->
  <up-popup :show="showFujiafeiEdit" mode="bottom" :round="10" @close="showFujiafeiEdit = false">
    <view>
      <view class="mb-10rpx w-full flex justify-center" @click="showFujiafeiEdit = false">
        <view class="h-10rpx w-30rpx rounded-full bg-[#ddd]" />
      </view>
      <view class="filter-content p-30rpx pb-10rpx">
        <view class="mb-16rpx flex items-center justify-between">
          <view class="flex items-center">
            <view class="mr-10rpx h-32rpx w-6rpx rounded-2rpx bg-[#07c160]" />
            <text class="text-32rpx text-[#333]">
              编辑附加费
            </text>
          </view>
          <view class="flex gap-20rpx">
            <text class="text-28rpx text-[#ff4d4f]" @click="deleteCurrentFujiafei">
              删除
            </text>
            <text class="text-28rpx text-[#07c160]" @click="saveFujiafeiEdit">
              保存
            </text>
          </view>
        </view>

        <view class="fujiafei-edit-form">
          <view class="fujiafei-edit-row">
            <text class="fujiafei-edit-label">
              名称
            </text>
            <input v-model="editingFujiafei.name" class="fujiafei-edit-input" placeholder="请输入附加费名称" disabled>
          </view>

          <view class="fujiafei-edit-row">
            <text class="fujiafei-edit-label">
              税率
            </text>
            <input v-model="editingFujiafei.rate" class="fujiafei-edit-input" type="digit" placeholder="请输入税率">
          </view>

          <view class="fujiafei-edit-row">
            <text class="fujiafei-edit-label">
              计算方式
            </text>
            <picker
              :value="getCalculationIndex(editingFujiafei.type)" :range="calculationOptions" range-key="type"
              class="fujiafei-edit-picker-wrapper" @change="onEditCalculationChange"
            >
              <view class="fujiafei-edit-picker">
                {{ getCalculationText(editingFujiafei.type) }}
                <image src="/static/images/select.png" class="picker-arrow-img" />
              </view>
            </picker>
          </view>

          <view class="fujiafei-edit-row">
            <text class="fujiafei-edit-label">
              支付方
            </text>
            <picker
              :value="getPayerIndex(editingFujiafei.method)" :range="payerOptions" range-key="type"
              class="fujiafei-edit-picker-wrapper" @change="onEditPayerChange"
            >
              <view class="fujiafei-edit-picker">
                {{ getPayerText(editingFujiafei.method) }}
                <image src="/static/images/select.png" class="picker-arrow-img" />
              </view>
            </picker>
          </view>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { onMounted, ref } from 'vue';
import {
  getCategoryTwo,
  getDayReport,
  getFujiafei,
  getGoodsUnit,
  getUnitData,
  uploadFile,
} from '@/api/category';
import { addSelf } from '@/api/order/index';
import * as S1Header from '@/components/S1Header.vue';

// 表单数据
const form = ref({
  goodsName: '', // 货品名称
  classify1: '', // 一级分类名称
  categoryId: '', // 一级分类ID
  classify2: '', // 二级分类名称
  categoryId2: '', // 二级分类ID
  imageUrl: '', // 图片URL
  saleUnit: '', // 销售单位
  defaultPriceUnit: 'sale', // 默认计价单位
  laborFee: '0.5', // 力资费
  invoiceFee: '2', // 开票费
  allowOverStock: true, // 是否允许超库存销售（默认允许）
  over_inventory: true, // 是否允许超库存销售（默认允许）
  huozhu_name: '', // a供货货主
  pici: '', // 车次批次
});

// 规则
const rules = ref({
  goodsName: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
  // classify1: [{ required: true, message: "请选择货品分类", trigger: "change" }], // 分类不是必填
});

// 状态变量
const showCategoryPicker = ref(false); // 分类选择器
const showUnitSelector = ref(false); // 单位选择弹窗
const showFujiafeiSelector = ref(false); // 附加费选择弹窗
const currentEditUnitIndex = ref(-1); // 当前编辑的单位索引
const categoryList = ref<any[]>([]); // 一级分类列表
const secondaryCategoryList = ref<any[]>([]); // 二级分类列表
const unitList = ref<any[]>([]); // 单位列表
const extendUnits = ref<any[]>([]); // 扩展单位列表
const select_fujiafei_list = ref<any[]>([]); // 附加费用列表
const fujiafeiList = ref<any[]>([]); // 所有附加费列表
const selectedFujiafeiIds = ref<number[]>([]); // 选中的附加费ID列表
const editShangpinId = ref(''); // 编辑商品ID
const addDraType = ref(1); // 抽屉类型：1新增，2编辑
const sell_type = ref(''); // 默认计价单位
const treeDataOne = ref<any[]>([]); // 一级分类数据
const treeDataTwo = ref<any[]>([]); // 二级分类数据
const chooseHeaderIndex = ref(4); // 头部索引，决定显示不同的表单项

// picker 相关状态
const categoryPickerRef = ref<any>(null); // picker 组件引用
const categoryColumns = ref<any[]>([]); // 分类选择器的列数据
const categoryLoading = ref(false); // 分类数据加载状态
const selectedPrimaryCategory = ref<any>(null); // 选中的一级分类
const selectedSecondaryCategory = ref<any>(null); // 选中的二级分类
const allSecondaryData = ref<any[]>([]); // 存储所有一级分类对应的二级分类数据

// 页面模式相关
const pageMode = ref<'add' | 'edit'>('add'); // 页面模式：新增或编辑
const editGoodsId = ref<string>(''); // 编辑的商品ID

// 附加费计算方式选项
const options = ref([
  { id: '1', type: '按单' },
  { id: '2', type: '按重量' },
  { id: '3', type: '按金额' },
]);

// 计算方式选项（新的）
const calculationOptions = ref([
  { id: '1', type: '乘重量' },
  { id: '2', type: '乘数量' },
  { id: '3', type: '直接加' },
  { id: '4', type: '按货款' },
]);

// 支付方选项
const payerOptions = ref([
  { id: '1', type: '货主出' },
  { id: '2', type: '买家出' },
]);

// 扩展单位（对应HTML中的guige数组）
const guige = ref<any[]>([]);

// 页面加载时获取URL参数
onLoad(async (options: any) => {
  if (options.mode === 'edit' && options.id) {
    pageMode.value = 'edit';
    editGoodsId.value = options.id;
    // 等待分类数据加载完成后再加载编辑数据
    await getCategoryData();
    await loadEditData();
  }
});

// 页面加载时获取分类数据和单位数据
onMounted(() => {
  // 如果不是编辑模式，才需要获取分类数据（编辑模式在onLoad中已经获取）
  if (pageMode.value !== 'edit') {
    getCategoryData();
  }
  getUnitListData();
  getFujiafeiData();
});

// 获取单位列表数据
async function getUnitListData() {
  try {
    const res = await getUnitData({} as any);
    if (res.code === 200 && res.data) {
      unitList.value = res.data || [];
      // 设置默认销售单位
      if (unitList.value.length > 0 && !form.value.saleUnit) {
        form.value.saleUnit = unitList.value[0].name;
        sell_type.value = unitList.value[0].name; // 设置默认计价单位
      }
    }
  }
  catch (error) {
    console.error('获取单位列表失败', error);
  }
}

// 获取分类数据
async function getCategoryData() {
  try {
    categoryLoading.value = true;
    const res = await getDayReport({
      page: 1,
      ishuozhuorfenlei: 1,
      limit: 10000,
      date: '', // 日期参数
    });

    if (res.code === 200 && res.data && res.data.data) {
      categoryList.value = res.data.data;
      // 转换为级联选择器数据格式
      treeDataOne.value = res.data.data.map((item: any) => {
        return {
          id: item.id,
          name: item.name,
          child: [],
        };
      });

      // 构建 picker 的列数据
      await buildCategoryColumns();
    }
  }
  catch (error) {
    console.error('获取分类失败', error);
  }
  finally {
    categoryLoading.value = false;
  }
}

// 获取二级分类数据
async function getSecondaryCategories(categoryId: string | number) {
  try {
    const res = await getCategoryTwo({
      name: Number(categoryId), // 分类ID
      page: 1,
      limit: 10000,
    });

    if (res.code === 200 && res.data) {
      secondaryCategoryList.value = res.data.data || [];
      // 转换为级联选择器数据格式
      treeDataTwo.value = res.data.data.map((item: any) => {
        return {
          id: item.id,
          name: item.name,
          child: [],
        };
      });
    }
  }
  catch (error) {
    console.error('获取二级分类失败', error);
  }
}

// 构建分类选择器的列数据
async function buildCategoryColumns() {
  // 第一列：一级分类
  const firstColumn = categoryList.value.map((item: any) => item.name);

  // 获取第一个一级分类的二级分类作为默认的第二列
  let secondColumn: string[] = ['不选择']; // 添加"不选择"选项作为第一个选项
  if (categoryList.value.length > 0) {
    try {
      const res = await getCategoryTwo({
        name: Number(categoryList.value[0].id),
        page: 1,
        limit: 10000,
      });

      if (res.code === 200 && res.data && res.data.data) {
        const secondaryNames = res.data.data.map((item: any) => item.name);
        secondColumn = ['不选择', ...secondaryNames]; // 在前面添加"不选择"选项
        // 存储第一个一级分类的二级分类数据（不包含"不选择"选项）
        allSecondaryData.value[0] = res.data.data;
      }
    }
    catch (error) {
      console.error('获取默认二级分类失败:', error);
    }
  }

  // 预加载所有一级分类的二级分类数据
  for (let i = 0; i < categoryList.value.length; i++) {
    const category = categoryList.value[i];
    try {
      const res = await getCategoryTwo({
        name: Number(category.id),
        page: 1,
        limit: 10000,
      });

      if (res.code === 200 && res.data && res.data.data) {
        allSecondaryData.value[i] = res.data.data;
      }
    }
    catch (error) {
      console.error(`获取分类 ${category.id} 的二级分类失败:`, error);
      allSecondaryData.value[i] = [];
    }
  }

  // 构建二维数组格式
  categoryColumns.value = [firstColumn, secondColumn];
}

// picker 列变化事件
function onCategoryChange(e: any) {
  const { columnIndex, index } = e;

  // 当第一列（一级分类）变化时，更新第二列（二级分类）
  if (columnIndex === 0 && allSecondaryData.value[index]) {
    const secondaryNames = allSecondaryData.value[index].map((item: any) => item.name);
    // 在二级分类前面添加"不选择"选项
    const secondColumnWithOption = ['不选择', ...secondaryNames];
    categoryPickerRef.value?.setColumnValues(1, secondColumnWithOption);
  }
}

// picker 确认选择
function onCategoryConfirm(e: any) {
  const { indexs } = e;

  // indexs[0] 是一级分类的索引，indexs[1] 是二级分类的索引
  if (indexs.length > 0) {
    const primaryIndex = indexs[0];
    const primaryCategory = categoryList.value[primaryIndex];

    if (primaryCategory) {
      form.value.classify1 = primaryCategory.name;
      form.value.categoryId = primaryCategory.id;
      selectedPrimaryCategory.value = primaryCategory;

      // 检查是否选择了二级分类
      if (indexs.length > 1 && indexs[1] !== undefined) {
        const secondaryIndex = indexs[1];

        // 如果选择的是"不选择"（索引为0），则清空二级分类
        if (secondaryIndex === 0) {
          form.value.classify2 = '';
          form.value.categoryId2 = '';
          selectedSecondaryCategory.value = null;
        }
        else {
          // 选择了具体的二级分类（索引需要减1，因为第0个是"不选择"）
          const actualSecondaryIndex = secondaryIndex - 1;
          if (allSecondaryData.value[primaryIndex] && allSecondaryData.value[primaryIndex][actualSecondaryIndex]) {
            const secondaryCategory = allSecondaryData.value[primaryIndex][actualSecondaryIndex];
            form.value.classify2 = secondaryCategory.name;
            form.value.categoryId2 = secondaryCategory.id;
            selectedSecondaryCategory.value = secondaryCategory;
          }
        }
      }
      else {
        // 没有选择二级分类，清空
        form.value.classify2 = '';
        form.value.categoryId2 = '';
        selectedSecondaryCategory.value = null;
      }
    }
  }

  showCategoryPicker.value = false;
}

// 通过分类ID获取分类名称
async function loadCategoryNames(catId: string | number, catId2?: string | number) {
  try {
    // 获取一级分类名称
    if (catId && categoryList.value.length > 0) {
      const primaryCategory = categoryList.value.find((item: any) => item.id == catId);
      if (primaryCategory) {
        form.value.classify1 = primaryCategory.name;
        selectedPrimaryCategory.value = {
          id: primaryCategory.id,
          name: primaryCategory.name,
        };
      }
    }

    // 获取二级分类名称
    if (catId2 && catId) {
      try {
        const res = await getCategoryTwo({
          name: Number(catId),
          page: 1,
          limit: 10000,
        });

        if (res.code === 200 && res.data && res.data.data) {
          const secondaryCategory = res.data.data.find((item: any) => item.id == catId2);
          if (secondaryCategory) {
            form.value.classify2 = secondaryCategory.name;
            selectedSecondaryCategory.value = {
              id: secondaryCategory.id,
              name: secondaryCategory.name,
            };
          }
        }
      }
      catch (error) {
        console.error('获取二级分类失败:', error);
      }
    }
  }
  catch (error) {
    console.error('加载分类名称失败:', error);
  }
}

// 加载编辑数据
async function loadEditData() {
  try {
    // 从缓存中获取编辑数据
    const editData = uni.getStorageSync('editGoodsData');
    console.log('获取到的编辑数据:', editData);
    if (editData) {
      // 填充表单数据
      form.value.goodsName = editData.goods_name || '';
      form.value.categoryId = editData.cat_id || '';
      form.value.categoryId2 = editData.cat_id_2 || '';

      // 设置编辑商品ID
      editShangpinId.value = editData.goods_id || '';
      console.log('设置编辑商品ID:', editData.goods_id);

      // 通过分类ID获取分类名称
      await loadCategoryNames(editData.cat_id, editData.cat_id_2);
      form.value.imageUrl = editData.original_img || '';
      form.value.saleUnit = editData.sell_type || '';
      form.value.defaultPriceUnit = editData.default_price_unit || 'sale';
      form.value.laborFee = editData.labor_fee || '0.5';
      form.value.invoiceFee = editData.invoice_fee || '2';
      form.value.allowOverStock = editData.over_inventory || true;
      form.value.over_inventory = editData.over_inventory || true;
      form.value.huozhu_name = editData.huozhu_name || '';
      form.value.pici = editData.pici || '';

      // 处理附加费数据
      if (editData.goods_fujiafei && editData.goods_fujiafei.length > 0) {
        select_fujiafei_list.value = editData.goods_fujiafei;
      }
      // 处理规格单位数据
      if (editData.goods_guige && editData.goods_guige.length > 0) {
        guige.value = editData.goods_guige.map((item: any) => ({
          id: item.id,
          unit: item.unit,
          num: item.num,
          is_default: item.is_default,
        }));
      }

      console.log('编辑数据加载完成:', editData);
    }
  }
  catch (error) {
    console.error('加载编辑数据失败:', error);
    uni.showToast({
      title: '加载数据失败',
      icon: 'none',
    });
  }
}

// 获取附加费用数据
async function getFujiafeiData() {
  try {
    const res = await getFujiafei([]);
    if (res.code === 200 && res.data) {
      // 保存所有附加费列表用于选择
      fujiafeiList.value = res.data.map((item: any) => {
        return {
          ...item,
          rate: item.rate || 0,
          method: item.method || '1',
          type: item.type || '1',
        };
      });

      // 默认不选择任何附加费
      // select_fujiafei_list.value = [];
      selectedFujiafeiIds.value = [];
    }
  }
  catch (error) {
    console.error('获取附加费用失败', error);
  }
}

// 获取计算方式文本
function getMethodText(method: string) {
  switch (method) {
    case '1':
      return '%';
    case '2':
      return '按重量';
    case '3':
      return '按金额';
    default:
      return '%';
  }
}

// 扩展单位
function extendUnit(type = '') {
  if (type !== 'change') {
    if (!form.value.saleUnit) {
      uni.showToast({
        title: '请先选择销售单位',
        icon: 'none',
      });
      return;
    }

    // 添加新的扩展单位
    guige.value.push({
      id: Date.now(),
      name: `二级单位`,
      unit: '',
      num: '',
      relation: form.value.saleUnit,
    });
  }
}

// 删除扩展单位
function extendUnitDel(id: number) {
  const index = guige.value.findIndex(item => item.id === id);
  if (index !== -1) {
    guige.value.splice(index, 1);
    // 如果删除的是默认计价单位，重置为销售单位
    if (sell_type.value === guige.value[index].unit) {
      sell_type.value = form.value.saleUnit;
    }
  }
}

// 选择单位
async function selectUnit(item: any) {
  form.value.saleUnit = item.name;
  sell_type.value = item.name; // 设置默认计价单位

  // 刷新扩展单位的关联单位
  guige.value.forEach((unit: any) => {
    unit.relation = form.value.saleUnit;
  });
  showUnitSelector.value = false;

  // 判断是否有二级、三级单位，有的话才调用接口
  if (guige.value && guige.value.length > 0) {
    // 切换单位时调用接口获取扩展单位数据
    await loadExtendUnitsData();
  }
}

// 加载扩展单位数据
async function loadExtendUnitsData() {
  if (!form.value.saleUnit) {
    return;
  }

  const requestData = {
    data: guige.value.map((item: any) => ({
      id: item.id,
      shouyin_id: item.shouyin_id || 19,
      name: item.name || '二级单位',
      unit: item.unit,
      num: item.num || '',
      relation: item.relation || form.value.saleUnit,
      goods_id: item.goods_id || 0,
    })),
    unit: form.value.saleUnit,
    editShangpinId: editShangpinId.value,
    chooseHeaderIndex: 1,
    type: 'change',
  };

  const res = await getGoodsUnit(requestData);
  if (res.code === 200 && res.data) {
    // 只有接口调用成功才全量更新guige数组
    guige.value = res.data.map((item: any) => ({
      id: item.id,
      shouyin_id: item.shouyin_id,
      name: item.name,
      unit: item.unit,
      num: item.num,
      relation: item.relation,
      goods_id: item.goods_id,
    }));
  }
  else {
    console.log('获取扩展单位数据失败:', res.msg);
    uni.showToast({
      title: res.msg || '获取扩展单位数据失败',
      icon: 'none',
    });
  }
}

// picker选择单位
async function selectUnitPicker(e: any, index: number) {
  const val = e.detail.value;
  guige.value[index].unit = unitList.value[val].name;

  // 选择单位后调用接口获取下级单位数据
  await loadExtendUnitsData();
}

// 获取分类显示文本
function getCategoryDisplayText() {
  if (form.value.classify1 && form.value.classify2) {
    return `${form.value.classify1} / ${form.value.classify2}`;
  }
  else if (form.value.classify1) {
    return form.value.classify1;
  }
  else {
    return '请选择分类';
  }
}

// 返回
function handleBack() {
  uni.navigateBack();
}

// 图片选择上传
function chooseImage() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    success: (res) => {
      uni.showLoading({ title: '上传中...' });

      uploadFile(res.tempFilePaths[0])
        .then((uploadRes: any) => {
          if (uploadRes.code === 200 && uploadRes.data.path) {
            form.value.imageUrl = uploadRes.data.path;
            uni.hideLoading();
            uni.showToast({ title: '上传成功', icon: 'success' });
          }
          else {
            throw new Error('上传失败');
          }
        })
        .catch((err: any) => {
          console.error('图片上传失败', err);
          uni.hideLoading();
          uni.showToast({ title: '上传失败', icon: 'error' });
        });
    },
  });
}

// 打开附加费用选择
function fujiafei() {
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  });
}

// 附加费用变更
function changeFujiafei() {
  console.log('附加费用变更', select_fujiafei_list.value);
}

// 删除附加费用
function fujiafeiDel(id: number) {
  const index = select_fujiafei_list.value.findIndex(item => item.id === id);
  if (index !== -1) {
    select_fujiafei_list.value.splice(index, 1);
  }
}

// 打开供货货主选择
function gonghuohuozhu() {
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  });
}

// 打开车次批次选择
function checipici() {
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  });
}

// 表单项变更
function formItemChange(val: string, field: string) {
  const fields = field.split('.');
  if (fields.length === 2) {
    const [obj, prop] = fields;
    if (obj === 'ruleForm') {
      form.value[prop as keyof typeof form.value] = val;
    }
  }
}

// 打开云货品库
function cloudGoodStatus() {
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  });
}

// 保存表单
async function handleSave() {
  // 验证表单
  if (!form.value.goodsName) {
    uni.showToast({
      title: '请输入货品名称',
      icon: 'none',
    });
    return;
  }

  // 分类不是必填，移除验证
  // if (!form.value.classify1) {
  //   uni.showToast({
  //     title: "请选择货品分类",
  //     icon: "none",
  //   });
  //   return;
  // }

  try {
    uni.showLoading({ title: '保存中...' });

    // 构建提交数据，按照您提供的参数格式
    const submitData: any = {
      addSelfDraType: pageMode.value === 'edit' ? 2 : 1, // 编辑模式为2，新增模式为1
      status: { isTrusted: true },
      editShangpinId: editShangpinId.value,
      goods_name: form.value.goodsName,
      cat_id: Number(form.value.categoryId),
      cat_id_2: Number(form.value.categoryId2) || 0,
      num: 0,
      type: 0,
      desk_price: 0,
      unit: form.value.saleUnit,
      goods_barcode: '',
      guige: guige.value.map((item: any) => ({
        id: item.id,
        shouyin_id: item.shouyin_id,
        name: item.name,
        unit: item.unit || '',
        num: item.num,
        relation: item.relation,
        goods_id: item.goods_id,
      })),
      fujiafei: select_fujiafei_list.value.map((item: any) => ({
        id: item.id,
        name: item.name,
        rate: item.rate,
        type: item.type,
        method: item.method,
        shouyin_id: item.shouyin_id,
        time: item.time || new Date().toISOString().slice(0, 19).replace('T', ' '),
        admin_id: item.admin_id,
        total: item.total,
      })),
      over_inventory: form.value.allowOverStock,
      sell_type: form.value.saleUnit,
      original_img: form.value.imageUrl || '',
    };

    console.log('提交数据', submitData);
    console.log('页面模式:', pageMode.value);
    console.log('editShangpinId:', editShangpinId.value);

    const res = await addSelf(submitData);

    if (res.code === 200) {
      uni.hideLoading();
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            handleBack();
          }, 1500);
        },
      });
    }
    else {
      uni.hideLoading();
      uni.showToast({
        title: res.msg || '保存失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('保存失败', error);
    uni.hideLoading();
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none',
    });
  }
}

// 用于编辑模式
function updateSelf(status: number) {
  if (status === 0) {
    uni.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success(res) {
        if (res.confirm) {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                handleBack();
              }, 1500);
            },
          });
        }
      },
    });
  }
}

// 表单关闭
function handleSelfClose() {
  handleBack();
}

// 确认提交（与handleSave功能相同，保留是为了对应HTML中的事件）
function determineSelf() {
  handleSave();
}

// 处理销售单位选择
async function handleSelectSaleUnit() {
  try {
    // 调用获取单位数据接口
    const res = await getUnitData({});
    if (res.code === 200 && res.data) {
      unitList.value = res.data || [];
      showUnitSelector.value = true;
    }
    else {
      uni.showToast({
        title: res.msg || '获取单位列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('获取单位列表失败', error);
    uni.showToast({
      title: '获取单位列表失败',
      icon: 'none',
    });
  }
}

// 配置单位或费用
async function onConfig(type: string) {
  if (type === 'unit') {
    if (!form.value.saleUnit) {
      uni.showToast({
        title: '请先选择销售单位',
        icon: 'none',
      });
      return;
    }
    // 准备要添加的新单位数据
    const newUnit = {
      id: Date.now(),
      shouyin_id: 19,
      name: '二级单位',
      unit: '',
      num: '',
      relation: form.value.saleUnit,
      goods_id: 0,
    };

    // 临时添加新单位到请求数据中
    const tempGuigeData = [...guige.value, newUnit];

    const requestData = {
      data: tempGuigeData.map((item: any) => ({
        id: item.id,
        shouyin_id: item.shouyin_id || 19,
        name: item.name || '二级单位',
        unit: item.unit,
        num: item.num || '',
        relation: item.relation || form.value.saleUnit,
        goods_id: item.goods_id || 0,
      })),
      unit: form.value.saleUnit,
      editShangpinId: editShangpinId.value,
      chooseHeaderIndex: chooseHeaderIndex.value,
    };

    const res = await getGoodsUnit(requestData);
    if (res.code === 200) {
      // 只有接口调用成功才全量更新guige数组
      guige.value = res.data.map((item: any) => ({
        id: item.id,
        shouyin_id: item.shouyin_id,
        name: item.name,
        unit: item.unit,
        num: item.num,
        relation: item.relation,
        goods_id: item.goods_id,
      }));
    }
  }
  else if (type === 'fee') {
    // 配置附加费
    await handleConfigFujiafei();
  }
}

// 处理附加费配置
async function handleConfigFujiafei() {
  try {
    // 先调用接口获取所有附加费列表
    const res = await getFujiafei([]);
    if (res.code === 200 && res.data) {
      fujiafeiList.value = res.data.map((item: any) => ({
        ...item,
        rate: item.rate || 0,
        method: item.method || '1',
        type: item.type || '1',
      }));

      // 设置当前已选择的附加费ID
      selectedFujiafeiIds.value = select_fujiafei_list.value.map((item: any) => item.id);

      // 显示选择弹窗
      showFujiafeiSelector.value = true;
    }
    else {
      uni.showToast({
        title: res.msg || '获取附加费列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('获取附加费列表失败', error);
    uni.showToast({
      title: '获取附加费列表失败',
      icon: 'none',
    });
  }
}

// 切换附加费选择状态
function toggleFujiafeiSelection(item: any) {
  const index = selectedFujiafeiIds.value.indexOf(item.id);
  if (index > -1) {
    // 取消选择
    selectedFujiafeiIds.value.splice(index, 1);
  }
  else {
    // 添加选择
    selectedFujiafeiIds.value.push(item.id);
  }
}

// 确认选择附加费
async function confirmSelectFujiafei() {
  try {
    // 获取选中的附加费名称数组
    const selectedNames = fujiafeiList.value
      .filter((item: any) => selectedFujiafeiIds.value.includes(item.id))
      .map((item: any) => item.name);

    if (selectedNames.length === 0) {
      // 如果没有选择任何附加费，清空列表
      select_fujiafei_list.value = [];
      showFujiafeiSelector.value = false;
      uni.showToast({
        title: '已清空附加费配置',
        icon: 'success',
      });
      return;
    }

    // 调用接口获取选中附加费的配置数据
    const res = await getFujiafei(selectedNames);
    if (res.code === 200 && res.data) {
      // 更新附加费列表
      select_fujiafei_list.value = res.data.map((item: any) => ({
        ...item,
        rate: item.rate || 0,
        method: item.method || '1',
        type: item.type || '1',
      }));

      showFujiafeiSelector.value = false;
      uni.showToast({
        title: '配置成功',
        icon: 'success',
      });
    }
    else {
      uni.showToast({
        title: res.msg || '配置失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('配置附加费失败', error);
    uni.showToast({
      title: '配置失败',
      icon: 'none',
    });
  }
}

// 附加费编辑相关函数
// 更新附加费字段
function updateFujiafei(index: number, field: string, value: string) {
  if (select_fujiafei_list.value[index]) {
    select_fujiafei_list.value[index][field] = value;
  }
}

// 删除附加费
function removeFujiafei(index: number) {
  select_fujiafei_list.value.splice(index, 1);
}

// 获取计算方式索引
function getCalculationIndex(type: string): number {
  return calculationOptions.value.findIndex(item => item.id === type);
}

// 获取计算方式文本
function getCalculationText(type: string): string {
  const option = calculationOptions.value.find(item => item.id === type);
  return option ? option.type : '乘重量';
}

// 计算方式变更
function onCalculationChange(e: any, index: number) {
  const selectedIndex = e.detail.value;
  const selectedOption = calculationOptions.value[selectedIndex];
  if (selectedOption && select_fujiafei_list.value[index]) {
    select_fujiafei_list.value[index].type = selectedOption.id;
  }
}

// 获取支付方索引
function getPayerIndex(method: string): number {
  return payerOptions.value.findIndex(item => item.id === method);
}

// 获取支付方文本
function getPayerText(method: string): string {
  const option = payerOptions.value.find(item => item.id === method);
  return option ? option.type : '货主出';
}

// 支付方变更
function onPayerChange(e: any, index: number) {
  const selectedIndex = e.detail.value;
  const selectedOption = payerOptions.value[selectedIndex];
  if (selectedOption && select_fujiafei_list.value[index]) {
    select_fujiafei_list.value[index].method = selectedOption.id;
  }
}

// 删除扩展单位
function removeExtendUnit(index: number) {
  const deletedItem = guige.value[index];
  guige.value.splice(index, 1);

  // 如果当前默认计价被删，重置为'sale'
  if (sell_type.value === deletedItem?.unit) {
    sell_type.value = form.value.saleUnit;
    form.value.defaultPriceUnit = 'sale';
  }
}

// 编辑附加费
const showFujiafeiEdit = ref(false);
const currentEditFujiafeiIndex = ref(-1);
const editingFujiafei = ref({
  name: '',
  rate: '',
  type: '1',
  method: '1',
});

function editFujiafei(index: number) {
  currentEditFujiafeiIndex.value = index;
  const item = select_fujiafei_list.value[index];
  editingFujiafei.value = {
    name: item.name || '',
    rate: item.rate || '',
    type: item.type || '1',
    method: item.method || '1',
  };
  showFujiafeiEdit.value = true;
}

// 保存附加费编辑
function saveFujiafeiEdit() {
  if (currentEditFujiafeiIndex.value >= 0) {
    const index = currentEditFujiafeiIndex.value;
    select_fujiafei_list.value[index] = {
      ...select_fujiafei_list.value[index],
      ...editingFujiafei.value,
    };
  }
  showFujiafeiEdit.value = false;
}

// 删除当前编辑的附加费
function deleteCurrentFujiafei() {
  if (currentEditFujiafeiIndex.value >= 0) {
    select_fujiafei_list.value.splice(currentEditFujiafeiIndex.value, 1);
    showFujiafeiEdit.value = false;
  }
}

// 获取重量单位
function getWeightUnit(): string {
  // 定义重量单位关键词
  const weightUnits = ['公斤', '斤', '吨', 'kg', 'KG', 't', 'T'];

  // 遍历规格单位，查找重量单位
  for (const item of guige.value) {
    if (item.unit && weightUnits.some(unit => item.unit.includes(unit))) {
      return item.unit;
    }
  }

  // 如果规格单位中没有重量单位，检查销售单位
  if (form.value.saleUnit && weightUnits.some(unit => form.value.saleUnit.includes(unit))) {
    return form.value.saleUnit;
  }

  // 默认返回公斤
  return '公斤';
}

// 获取计算方式单位
function getCalculationUnit(type: string): string {
  switch (type) {
    case '1': // 乘重量
      return `元/${getWeightUnit()}`;
    case '2': // 乘数量
      return '元/件';
    case '3': // 直接加
      return '元';
    case '4': // 按货款
      return '元';
    default:
      return '元';
  }
}

// 编辑弹窗中的计算方式变更
function onEditCalculationChange(e: any) {
  const selectedIndex = e.detail.value;
  const selectedOption = calculationOptions.value[selectedIndex];
  if (selectedOption) {
    editingFujiafei.value.type = selectedOption.id;
  }
}

// 编辑弹窗中的支付方变更
function onEditPayerChange(e: any) {
  const selectedIndex = e.detail.value;
  const selectedOption = payerOptions.value[selectedIndex];
  if (selectedOption) {
    editingFujiafei.value.method = selectedOption.id;
  }
}
</script>

<style scoped>
.form-scroll {
  flex: 1;
  overflow-y: auto;
  height: 0;
  min-height: 0;
}

.section-title {
  font-size: 32rpx;
  padding: 32rpx 24rpx 16rpx;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-text {
  font-size: 28rpx;
  color: #409eff;
  font-weight: normal;
}

.form-row {
  display: flex;
  align-items: center;
  min-height: 96rpx;
  padding: 0 24rpx;
  border-bottom: 1px solid rgba(232, 231, 231, 0.39);
}

.form-label {
  flex: 0 0 180rpx;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(108, 106, 102, 1);
}

.form-label-switch {
  font-size: 16px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(51, 51, 51, 1);
}

.form-input {
  flex: 1;
  text-align: right;
  font-size: 28rpx;
  color: #222;
}

.form-arrow::after {
  content: ">";
  display: inline-block;
  margin-left: 12rpx;
  color: #bbb;
  transform: scaleY(1.5);
}

.image-row {
  align-items: flex-start;
  padding-top: 18rpx;
  padding-bottom: 18rpx;
}

.form-desc {
  font-size: 22rpx;
  color: #aaa;
  margin-top: 4rpx;
}

.upload-area {
  width: 200rpx;
  height: 200rpx;
  background-color: #f7f7f7;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  border-radius: 8rpx;
}

.camera-icon {
  color: #e0e0e0;
  font-size: 90rpx;
}

.upload-preview {
  width: 100%;
  height: 100%;
}

.value-text {
  font-weight: normal;
}

.value-desc {
  font-size: 24rpx;
  color: #999;
  margin-left: 4rpx;
}

.save-btn-wrap {
  margin: 60rpx 32rpx;
}

.section-gap {
  height: 24rpx;
  background-color: #f5f5f5;
  width: 100%;
}

.single-card {
  background: #fff;
  width: 100%;
}

.form-row.no-border {
  border-bottom: none;
}

.switch-row {
  justify-content: space-between;
  align-items: center;
}

.config-btn {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(21, 232, 70, 1);
}

.fujiafei-title-text {
  font-size: 16px;
  font-weight: 700;
  letter-spacing: 0px;
  color: rgba(51, 51, 51, 1);
}

.config-arrow {
  font-size: 15px;
  margin-left: 4rpx;
  color: #bdbdbd;
}

.specs-section {
  background-color: #fff;
  padding: 0 30rpx;
}

.specs-title {
  font-size: 32rpx;
  margin: 20rpx 0;
  color: #333;
}

.spec-row {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.spec-label {
  width: 150rpx;
  font-size: 28rpx;
  color: #333;
}

.spec-unit-select {
  width: 150rpx;
  height: 60rpx;
  border: 1px solid #ddd;
  border-radius: 4rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10rpx;
  margin-right: 30rpx;
}

.unit-value {
  font-size: 28rpx;
  color: #333;
}

.unit-arrow {
  font-size: 24rpx;
  color: #999;
}

.spec-price-default {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.radio-circle {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10rpx;
}

.radio-inner {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #07c160;
}

.spec-quantity {
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-left: 150rpx;
  font-size: 28rpx;
  color: #333;
}

.quantity-input {
  display: flex;
  align-items: center;
  margin: 0 20rpx;
}

.quantity-input input {
  width: 120rpx;
  height: 60rpx;
  border: 1px solid #ddd;
  border-radius: 4rpx;
  padding: 0 10rpx;
  text-align: center;
}

.quantity-unit {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.delete-btn {
  color: #ff4d4f;
  font-size: 28rpx;
  margin-left: auto;
}

.unit-card {
  border: 1px solid #ff4d4f;
  border-radius: 8rpx;
  margin: 20rpx 24rpx 0 24rpx;
  padding: 24rpx;
  background: #fff;
}

.unit-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.unit-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #333;
}

.unit-input {
  flex: 1;
  height: 56rpx;
  border: 1px solid #ddd;
  border-radius: 4rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.unit-select {
  flex: 1;
  height: 56rpx;
  border: 1px solid #ddd;
  border-radius: 4rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
}

.radio-wrap {
  display: flex;
  align-items: center;
  margin-left: 16rpx;
}

.radio-circle {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  border: 2rpx solid #bbb;
  margin-right: 8rpx;
  background: #f5f5f5;
}

.radio-circle.active {
  border-color: #07c160;
}

.radio-label {
  color: #bbb;
  font-size: 28rpx;
}

.radio-label.active {
  color: #07c160;
}

.unit-desc {
  margin-left: 16rpx;
  color: #333;
  font-size: 28rpx;
}

.unit-row-actions {
  justify-content: flex-end;
}

.delete-btn {
  color: #ff4d4f;
  font-size: 36rpx;
  cursor: pointer;
}

.iconfont.icon-delete:before {
  content: "\e6a6";
}

.unit-card-v2 {
  background: #fff;
  border-radius: 2px;
  margin: 0 0 24rpx 0;
  padding: 0 24rpx;
  box-shadow: none;
}

.unit-row-v2 {
  display: flex;
  align-items: center;
  min-height: 36px;
  font-size: 13px;
  padding: 0;
}

.unit-label-v2 {
  color: #666;
  width: 90px;
  font-size: 13px;
  flex-shrink: 0;
}

.unit-value-v2 {
  color: #222;
  font-size: 14px;
  margin-right: 16px;
}

.unit-select-v2 {
  min-width: 70px;
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 2px;
  padding: 0 10px;
  height: 26px;
  display: flex;
  align-items: center;
  margin-right: 16px;
  font-size: 13px;
  color: #222;
}

.unit-input-v2 {
  width: 50px;
  height: 26px;
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 2px;
  text-align: center;
  font-size: 13px;
  margin-right: 8px;
}

.unit-desc-v2 {
  background: #f5f6fa;
  border-radius: 2px;
  padding: 0 8px;
  color: #222;
  font-size: 13px;
  height: 26px;
  display: flex;
  align-items: center;
  margin-right: 8px;
}

.radio-wrap-v2 {
  display: flex;
  align-items: center;
  margin-left: auto;
  cursor: pointer;
  user-select: none;
  gap: 4px;
}

.radio-circle-v2 {
  width: 14px;
  height: 14px;
  border: 2px solid #bdbdbd;
  border-radius: 50%;
  background: #fff;
  position: relative;
  box-sizing: border-box;
  transition: border-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-circle-v2.active {
  border-color: #21c16c;
}

.radio-circle-v2.active::after {
  content: "";
  position: absolute;
  left: 3px;
  top: 3px;
  width: 5px;
  height: 5px;
  background: #21c16c;
  border-radius: 50%;
  display: block;
}

.radio-label-v2 {
  color: #bdbdbd;
  font-size: 13px;
  font-weight: 500;
  transition: color 0.2s;
  display: flex;
  align-items: center;
  height: 100%;
}

.unit-scroll-container {
  max-height: 400rpx;
  margin-top: 10rpx;
}

.fujiafei-scroll-container {
  max-height: 400rpx;
  margin-top: 10rpx;
}

.radio-label-v2.active {
  color: #21c16c;
}

.delete-btn-v2 {
  margin-left: auto;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #ff4d4f;
}

.delete-btn-v2 .icon {
  display: block;
}

.divider-v2 {
  height: 1px;
  background: #f0f0f0;
  margin: 0 0 0 0;
}

.spec-group {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 2px;
  overflow: hidden;
  box-shadow: 0 0 0 1px #e5e6eb;
  height: 28px;
  margin-right: 8px;
}

.spec-input {
  width: 40px;
  height: 28px;
  border: none;
  outline: none;
  background: #fff;
  text-align: center;
  font-size: 13px;
  border-radius: 2px 0 0 2px;
  padding: 0 8px;
}

.spec-desc {
  background: #f5f6fa;
  color: #222;
  font-size: 13px;
  height: 28px;
  display: flex;
  align-items: center;
  padding: 0 8px;
  border-radius: 0 2px 2px 0;
}

/* 附加费卡片样式 */
.fujiafei-card {
  background: #fff;
  border-radius: 8rpx;
  margin: 0 0 16rpx 0;
  padding: 24rpx;
  border: 1px solid #e8e7e7;
}

.fujiafei-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #f0f0f0;
}

.fujiafei-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.fujiafei-delete {
  font-size: 28rpx;
  color: #ff4d4f;
  cursor: pointer;
}

.fujiafei-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  min-height: 60rpx;
}

.fujiafei-row:last-child {
  margin-bottom: 0;
}

.fujiafei-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
}

.fujiafei-input {
  flex: 1;
  height: 60rpx;
  border: 1px solid #e5e6eb;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
}

.fujiafei-picker {
  flex: 1;
  height: 60rpx;
  border: 1px solid #e5e6eb;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker-arrow {
  color: #bbb;
  font-size: 24rpx;
}

/* 附加费列表项样式 */
.fujiafei-item {
  display: flex;
  align-items: center;
  min-height: 96rpx;
  padding: 0 24rpx;
  border-bottom: 1px solid rgba(232, 231, 231, 0.39);
  background: #fff;
  cursor: pointer;
}

.fujiafei-item:active {
  background: #f5f5f5;
}

.fujiafei-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.fujiafei-name {
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(108, 106, 102, 1);
}

.fujiafei-amount {
  font-size: 15px;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(154, 156, 161, 1);
  text-align: right;
}

/* 附加费编辑弹窗样式 */
.fujiafei-edit-form {
  margin-top: 20rpx;
}

.fujiafei-edit-row {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  min-height: 60rpx;
}

.fujiafei-edit-row:last-child {
  margin-bottom: 0;
}

.fujiafei-edit-label {
  width: 140rpx;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
}

.fujiafei-edit-input {
  flex: 1;
  width: 100%;
  height: 60rpx;
  border: 1px solid #e5e6eb;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
  box-sizing: border-box;
}

.fujiafei-edit-input:disabled {
  background: #f5f5f5;
  color: #999;
}

.fujiafei-edit-picker-wrapper {
  flex: 1;
  width: 100%;
  display: block;
}

.fujiafei-edit-picker {
  flex: 1;
  width: 100%;
  height: 60rpx;
  border: 1px solid #e5e6eb;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 28rpx;
  color: #333;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.picker-arrow-img {
  width: 5px;
  height: 10px;
  flex-shrink: 0;
}

/* 通用右箭头图片样式 */
.right-arrow-img {
  width: 5px;
  height: 10px;
  flex-shrink: 0;
  margin-left: 8rpx;
}
</style>
